package com.fsnmt.xxx;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.fsnmt.maizhuanbao.UnityPlayerNativeActivity;
import com.fsnmt.maizhuanbao.bean.Device;
import com.fsnmt.maizhuanbao.printfUtils.PrintfManager;
import com.fsnmt.maizhuanbao.printfUtils.SharedPreferencesManager;
import com.fsnmt.maizhuanbao.qrcodeUtils.ZXingUtil;
import com.fsnmt.maizhuanbao.utils.CacheManager;
import com.fsnmt.maizhuanbao.utils.DeviceUtils;
import com.fsnmt.maizhuanbao.utils.LogUtils;
import com.fsnmt.maizhuanbao.utils.PicturePickUtils;
import com.fsnmt.maizhuanbao.utils.SystemUtils;
import com.fsnmt.maizhuanbao.utils.ToastUtils;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;

public class MainActivity extends AppCompatActivity {

	Device device;
	ImageView image;
	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setContentView(R.layout.activity_main);
		image = (ImageView) findViewById(R.id.image);
		((Button)findViewById(R.id.btn_init)).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				_InitPrintf();
			}
		});
		((Button)findViewById(R.id.btn_printf)).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
//				_StartPrintf("http://www.baidu.com","好久不见","1");
				printfBitmap("http://www.baidu.com","好久不见");
			}
		});
		((Button)findViewById(R.id.btn_setting)).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				_OpenBuletoothSetting();
			}
		});
		((Button)findViewById(R.id.btn_search)).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if(Build.VERSION.SDK_INT < 24){
					_StartSearchPrintfDevice();
				}else {
					if (SystemUtils.checkLocationPermission(MainActivity.this)) {
						_StartSearchPrintfDevice();
					} else {
						ToastUtils.show(MainActivity.this, "请求定位权限");
						SystemUtils.getLocationPermission(MainActivity.this);
					}
				}

			}
		});
		((Button)findViewById(R.id.btn_stop_search)).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				_StopSearchBlueTooth();
			}
		});
		((Button)findViewById(R.id.btn_connect)).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if(null!=device) {
					_ConnectPrintfDevice(device.name, device.address);
				}
			}
		});
		((Button)findViewById(R.id.btn_break)).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if(printfManager.isConnect()) {
					printfManager.disConnect("断开成功");
				}
			}
		});
	}



	@Override
	public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
		switch (requestCode) {
			case SystemUtils.RequestCode.REQUEST_CODE_LOCATION:
				if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
					_StartSearchPrintfDevice();
				} else {
					ToastUtils.show(this, "请允许该权限");
				}
			default:
				super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		}
	}




	/**蓝牙打印接口**************************/
	PrintfManager printfManager;
	private AbstractList<BluetoothDevice> bluetoothDeviceArrayList;
	private boolean isRegister = false;
	private final int ImageWidth = 380;
	private final int QRCodeWidth = 340;
	private BluetoothAdapter mBluetoothAdapter = null;
	private static int REQUEST_ENABLE_BT = 2;

	public void _InitPrintf(){
		LogUtils.show("initPrintf()");
		isRegister = false;
		bluetoothDeviceArrayList = new ArrayList<>();
		printfManager = PrintfManager.getInstance(this);
		printfManager.setConnectSuccess(new PrintfManager.ConnectSuccess() {
			@Override
			public void success() {
				LogUtils.show("connectSuccess");
				String bluetoothName = SharedPreferencesManager.getBluetoothName(MainActivity.this);
				String bluetoothAddress = SharedPreferencesManager.getBluetoothAddress(MainActivity.this);
				ToastUtils.show(MainActivity.this,"蓝牙连接成功："+bluetoothName);
//				UnityPlayer.UnitySendMessage("ExternalAccess", "setPrintfConnectStatus", "1");
//				UnityPlayer.UnitySendMessage("ExternalAccess", "setCurrentConnectPrintfDevice", bluetoothName+","+bluetoothAddress);
			}
		});
		printfManager.defaultConnection();
	}

	public void _StartPrintf(String url,String content,String cont){
		LogUtils.show("startPrintf()");
		if(printfManager.isCONNECTING()){
//			UnityPlayer.UnitySendMessage("ExternalAccess", "setPrintfConnectStatus", "2");
			ToastUtils.show(this,"蓝牙正在连接，请稍候。");
			return;
		}
		if(TextUtils.isEmpty(url) || TextUtils.isEmpty(content) || TextUtils.isEmpty(cont)){
			ToastUtils.show(this,"打印内容为空");
			return;
		}else{
			ToastUtils.show(this,""+url+","+content+","+cont);
		}
		isRegister = false;
		if(printfManager.isConnect()){
			LogUtils.show("printfBitmap()");
			printfBitmap( url, content);
		}else{
			LogUtils.show("setPrintfConnectStatus 0 未连接打印机");
//			UnityPlayer.UnitySendMessage("ExternalAccess", "setPrintfConnectStatus", "0");
			mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
			if(null!=mBluetoothAdapter && mBluetoothAdapter.isEnabled()) {//蓝牙已经开启
				LogUtils.show("setBluetoochStatus 1 蓝牙已开");
//				UnityPlayer.UnitySendMessage("ExternalAccess", "setBluetoochStatus", "1");
			}else{//蓝牙没有开
				LogUtils.show("setBluetoochStatus 0 蓝牙没开");
//				UnityPlayer.UnitySendMessage("ExternalAccess", "setBluetoochStatus", "0");
			}
		}
	}

	private void printfBitmap(String url, String content) {
		Bitmap bitmap = Bitmap.createBitmap(ImageWidth, ImageWidth, Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(bitmap);
		canvas.drawColor(Color.WHITE);

		Bitmap bitmap1 = ZXingUtil.encodeQRCode(url, QRCodeWidth, QRCodeWidth);
		canvas.drawBitmap(bitmap1, (ImageWidth-QRCodeWidth)/2, 0, new Paint());

		Paint paint = new Paint();
		paint.setColor(Color.BLACK);
//		int textSize = DeviceUtils.dip2px(this, 14);
//		LogUtils.show("textSize = "+textSize);
		paint.setTextSize(32);
		paint.setAntiAlias(true);
		float fontWidth = paint.measureText(content);
		canvas.drawText(content, (ImageWidth - fontWidth) / 2, ImageWidth-38, paint);

		try {
			Matrix  m = new Matrix();
			m.setRotate(180, (float) ImageWidth / 2, (float) ImageWidth / 2);
			Bitmap bm1 = Bitmap.createBitmap(bitmap, 0, 0, ImageWidth, ImageWidth, m, true);
			image.setImageBitmap(bm1);
//			printfManager.printf(48,50,bm1,this);
		} catch (OutOfMemoryError ex) {
			image.setImageBitmap(bitmap);
//			printfManager.printf(48,50,bitmap,this);
		}
	}


	public void _OpenBuletoothSetting(){
//		Intent intent = new Intent();
//		intent.setAction(Settings.ACTION_BLUETOOTH_SETTINGS);
//		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//		try{
//			startActivity(intent);
//		} catch(ActivityNotFoundException ex){
//			ToastUtils.show(this,"跳转失败，请手动打开蓝牙。");
//		}catch (Exception e){
//			ToastUtils.show(this,"跳转失败，请手动打开蓝牙。");
//		}
		LogUtils.show("openBluetoothSetting()");
		Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
		startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
	}


	public void _StartSearchPrintfDevice(){
		LogUtils.show("startSearchPrintfDevice()");
		bluetoothDeviceArrayList.clear();
		ToastUtils.show(this, "正在搜索");
		IntentFilter filter = new IntentFilter();
		filter.addAction(BluetoothDevice.ACTION_FOUND);
		filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		registerReceiver(mReceiver, filter);
		isRegister = true;
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
			Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
			startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
		} else {
			mBluetoothAdapter.startDiscovery();
//			UnityPlayer.UnitySendMessage("ExternalAccess", "setBluetoochStatus", "2");
		}
	}


	public void _StopSearchBlueTooth(){
		if (mReceiver != null && isRegister) {
			try {
				LogUtils.show("stopSearchPrintfDevice()");
//				UnityPlayer.UnitySendMessage("ExternalAccess", "setBluetoochStatus", "3");
				unregisterReceiver(mReceiver);
				isRegister = false;
				ToastUtils.show(this, "搜索完成");
			}catch (Exception e){
			}
		}
	}



	public void _ConnectPrintfDevice(String name, final String address){
		LogUtils.show("connectPrintfDevice()");
		//先停止搜索
		_StopSearchBlueTooth();
		ToastUtils.show(this, "正在连接...");
//		UnityPlayer.UnitySendMessage("ExternalAccess", "setPrintfConnectStatus", "2");
		//进行配对
		Executors.newCachedThreadPool().execute(new Runnable() {
			@Override
			public void run() {
				try {
					BluetoothDevice mDevice = mBluetoothAdapter.getRemoteDevice(address);
					printfManager.openPrinter(mDevice);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}


	private BroadcastReceiver mReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			//找到设备
			if (BluetoothDevice.ACTION_FOUND.equals(action)) {
				BluetoothDevice device = intent
						.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				if (judge(device,bluetoothDeviceArrayList))
					return;
				bluetoothDeviceArrayList.add(device);
				Device device1 = new Device(device.getName(), device.getAddress());
				ToastUtils.show(MainActivity.this,"搜索到"+device.getName()+","+device.getAddress());
				MainActivity.this.device = device1;
				String s = device1.toString();
				LogUtils.show("find device "+s);
//				UnityPlayer.UnitySendMessage("ExternalAccess", "setNewBluetoochDevice", s);
			}
			//搜索完成
			else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
				_StopSearchBlueTooth();
			}
		}
	};

	private boolean judge(BluetoothDevice device, List<BluetoothDevice> devices) {
		if (device == null || devices.contains(device)) {
			return true;
		}
		int majorDeviceClass = device.getBluetoothClass().getMajorDeviceClass();
		if(majorDeviceClass != 1536){
			return true;
		}
		return false;
	}
	/*************************************/
}
